package com.ty.service;

import cn.hutool.core.date.DateUtil;
import cn.smart.core.util.UserContext;
import com.ty.dao.IoItemDao;
import com.ty.dao.PoMasterDao;
import com.ty.dto.InventoryChangSource;
import com.ty.entity.IoItem;
import com.ty.entity.IoMasterQuery;
import com.ty.enums.InventoryChangType;
import com.ty.enums.PoStatus;
import com.ty.event.InventoryChangEvent;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import com.ty.entity.IoMaster;
import com.ty.dao.IoMasterDao;
import com.ty.service.IoMasterService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * ;(212_io_master)表服务实现类
 * @author : heimi
 * @date : 2025-6-7
 */
@Service
public class IoMasterService{
     
    @Autowired
    private IoMasterDao ioMasterDao;
    @Autowired
    private IoItemDao ioItemDao;
    @Autowired
    private PoMasterDao poMasterDao;

    public List<IoMaster> select(IoMasterQuery query) {
        return ioMasterDao.select(query);
    }
    
    public Integer insert(IoMaster ioMaster) {
        //1.验证
        //验证采购单是否已经入库
        //2.组装数据
        String ioId ="IO"+ DateUtil.format(DateUtil.date(),"yyyyMMddHHmmssSSS");
        ioMaster.setId(ioId);
        List<IoItem> ioItems =ioMaster.getIoItems();
        for(IoItem item :ioItems){
            item.setIoid(ioId);
            item.setLastUpdateBy(UserContext.get().getNickName());
            item.setExpirydate(item.getProductiondate().plusDays(item.getShelflife()));
        }
        //3.落库
        IoMasterService aop = (IoMasterService) (AopContext.currentProxy());
        aop.save(ioMaster);
        return 1;
    }

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    @Transactional
    public void save(IoMaster ioMaster){
        ioMasterDao.insert(ioMaster);
        ioItemDao.insertBatch(ioMaster.getIoItems());
        poMasterDao.updateStatus(ioMaster.getPoid(), PoStatus.FINISH.getCode());

        InventoryChangSource source = new InventoryChangSource();
        source.setType(InventoryChangType.IN); //类型是入库
        source.setRefId(ioMaster.getId()); // refid 就是入库单id
        InventoryChangEvent inventoryChangEvent = new InventoryChangEvent(source);

        //使用观察者模式 - 解耦
        applicationEventPublisher.publishEvent(inventoryChangEvent);
    }
    
    public Integer update(IoMaster ioMaster) {
        return ioMasterDao.update(ioMaster);
    }
    
    public Integer delete(Integer id) {
        return ioMasterDao.delete(id);
    }
    
}